import { addUrlPerFix } from "@/basa/utils";
import { exportData, showLoading } from "@/basa/utils/public";
import { mapGetters } from "vuex";
import Cookies from "js-cookie";
export default {
  data() {
    return {
      uploadUrl: addUrlPerFix(process.env.VUE_APP_UPLOAD_URL), //上传图片
      headers: {
        Authorization: Cookies.get("access_token") || ""
      },
      uploadLoading: null,
      fileList: [],
      uploadList: []
    };
  },
  created() {
    this.init();
  },
  deactivated() {
    this.fileList = [];
    this.uploadList = [];
  },
  methods: {
    deleteAppend(index) {
      this.fileList.splice(index, 1);
      this.uploadList.splice(index, 1);
    },

    downLoad({ ossUrl, fileName }) {
      // 组合
      const fileData = { ossUrl, fileName };
      // 下载
      exportData(fileData);
    },

    beforeUpload({ name, size }) {
      const suffix = name.substring(name.lastIndexOf("."));
      let fileType = this.getUploadFileRules.includes(suffix.toLowerCase());
      let fileSize = size > 50 * 1024 * 1024;


      if (!fileType) {
        this.$showErrorMessage("上传文件格式错误！");
      } else if (fileSize) {
        this.$showErrorMessage("文件大小不可超过50M！");
      } else if (size === 0) {
        this.$showErrorMessage("文件大小不可为0B！");
      }

      return fileType && !fileSize && !!size;
    },

    onError({ message }) {
      this.$showErrorMessage("附件上传失败");
      this.uploadLoading.close();
    },

    onProgress(event, file, fileList) {
      this.uploadLoading = showLoading("上传中");
    },

    handleBlur(row) {
      const index = this.fileList.findIndex(_ => _.onlyId === row.onlyId);
      this.uploadList[index].fileDesc = row.fileDesc;
    }
  },
  watch: {
    uploadList(newVal) {
      this.$emit("uploadSuccess", newVal);
    }
  },
  computed: {
    ...mapGetters(["getUploadFileRules"])
  }
};
